package tjs.study.mini.mybatismini.simpleAop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import tjs.study.mini.mybatismini.config.proxy.MapperProxy;

import javax.sql.DataSource;
import java.lang.reflect.InvocationHandler;

/**
 * @author nicky
 * @date 2021/9/6 下午4:52
 */
@Aspect
public class AopMapperAspect {
    private DataSource dataSource;

    public AopMapperAspect(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Pointcut(value = "@within(tjs.study.mini.mybatismini.simpleAop.AopMiniMapper)")
    public void point() {
    }

    @Around("point()")
    public Object around(ProceedingJoinPoint pj) throws Throwable {
        InvocationHandler invocationHandler = new MapperProxy(dataSource);
        Signature signature = pj.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;

        return invocationHandler.invoke(pj.getThis(), methodSignature.getMethod(), pj.getArgs());
    }
}
